package com.mills.gamebase.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.annotation.Transactional;

import com.mills.gamebase.dao.IViewDAO;
import com.mills.gamebase.model.View;
import com.mills.gamebase.service.DAO;

/**
 * Implementierung des Interfaces {@linkplain IViewDAO}
 * 
 * @author Shane
 *
 */
public class ViewDAO extends AbstractDAO<View> implements IViewDAO {

	public ViewDAO() {
		logger = Logger.getLogger(ViewDAO.class);
		entityClazz = View.class;
		entityModelName = "View";
	}
	
	@Override
	protected void preload(View entity, String... preloads) {
		for (String preload : preloads) {
			if (preload.equals(PRELOAD_ROLES) || preload.equals(DAO.PRELOAD_ALL)) {
				if (entity.getRoles() != null) entity.getRoles().size();
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public View get(String urlPattern, String... preloads) {
		if (logger.isDebugEnabled()) {
			logger.debug("Loading View with urlpattern='"+urlPattern+"'...");
		}
		
		List<View> v = new ArrayList<View>();
		try {
			v = sessionFactory.getCurrentSession().createQuery("select v from View as v where v.urlpattern like '" + urlPattern + "'").list();
		} catch (DataAccessException e) {
			logger.error("Exception caught Loading View with urlpattern='"+urlPattern+"'!", e);
		}
		
		if (v.size() > 0)
		{
			if (logger.isDebugEnabled()) {
				logger.debug("View with urlpattern='"+urlPattern+"' successfully loaded.");
			}
			preload(v.get(0), preloads);
			return v.get(0);
		}
		
		logger.error("No View found with urlpattern='"+urlPattern+"'!");
		
		return null;
	}

	public boolean patternExists(String pattern, Long id) {
		if (logger.isDebugEnabled()) {
			logger.debug("Checking existence of urlpattern '" + pattern + "'");
		}
		
		try {
			return !sessionFactory.getCurrentSession().createQuery("select v from View as v where v.urlpattern = '" + pattern + "' and v.id != "+ id).list().isEmpty();
		} catch (Exception e) {
			logger.error("Exception caught checking existence of urlpattern '" + pattern + "'!", e);
		}
		
		return false;
	}

}
